package cn.com.youjile.service;

import cn.com.youjile.entity.MsgInfo;
import cn.com.youjile.observer.MsgObserver;
import cn.com.youjile.observer.MsgSubject;
import cn.com.youjile.protobuf.UserInfo;
import cn.com.youjile.utils.MsgInfoFactory;
import cn.com.youjile.utils.MsgNumUtil;
import cn.com.youjile.utils.ResultUtil;
import com.google.protobuf.InvalidProtocolBufferException;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @Author michael.yang
 * @CreateDate 2021/3/18
 * @Describe
 */
@Slf4j
@Service
public class Login extends MsgObserver {

    public Login(){
        MsgSubject.getInstance().attach(this);
    }

    @Override
    public void update(ChannelHandlerContext ctx, MsgInfo msg) {
        if(msg.getCode() == MsgNumUtil.s_login) {
            byte[] info = msg.getInfo();
            try {
                UserInfo.User user = UserInfo.User.parseFrom(info);
                /**
                 * 这里处理登录逻辑
                 */
                //响应登录消息
                byte[] success = ResultUtil.success("登录成功");
                MsgInfo msgInfo = MsgInfoFactory.buildMessageInfo(MsgNumUtil.success, success);
                ctx.writeAndFlush(msgInfo);
            } catch (InvalidProtocolBufferException e) {
                e.printStackTrace();
                //登录异常，回复客户端用户
                byte[] error = ResultUtil.error("消息解析异常，请检查！");
                MsgInfo msgInfo = MsgInfoFactory.buildMessageInfo(MsgNumUtil.error, error);
                ctx.writeAndFlush(msgInfo);
            }
        }
    }
}
